package qq

import (
	"api-go/serializer"
	"api-go/util"
	"net/url"
	"strconv"
)

// 搜索所需信息
type Search struct {
	Key    string `form:"key"`
	Limit  string `form:"limit"`
	Offset string `form:"offset"`
	Type   string `form:"type"`
}

//获取搜索信息
func (service *Search) SearchInfo() *serializer.Response {

	if val := service.Key; val != "" {
		service.Key = val
	} else {
		service.Key = "周杰伦"
	}

	if val := service.Limit; val != "" {
		service.Limit = val
	} else {
		service.Limit = "30"
	}

	if val := service.Offset; val != "" {
		service.Offset = val
	} else {
		service.Offset = "1"
	}

	// 关键字搜索（ 0：单曲，2：歌单，3:用户 ,7：歌词，8：专辑，9：歌手，12：mv）
	if val := service.Type; val != "" {
		service.Type = val
	} else {
		service.Type = "1"
	}
	//1: 单曲, 2: 专辑, 3: 歌手, 4: 用户, 5: MV, 6: 歌词，9：歌单
	switch service.Type {
	case "1":
		service.Type = "0"
	case "2":
		service.Type = "8"
	case "3":
		service.Type = "9"
	case "4":
		service.Type = "3"
	case "5":
		service.Type = "12"
	case "6":
		service.Type = "7"
	case "9":
		service.Type = "2"
	default:
		service.Type = "0"
	}
	//此处需要对中文进行转码，否则会无法请求第三方api
	service.Key = url.QueryEscape(service.Key)

	newOffset, _ := strconv.ParseInt(service.Offset, 10, 64)
	var url string
	if service.Type == "0" || service.Type == "7" || service.Type == "8" || service.Type == "9" || service.Type == "12" {
		url = "https://c.y.qq.com/soso/fcgi-bin/client_search_cp?t=" + service.Type + "&cr=1&p=" + service.Offset + "&n=" + service.Limit + "&w=" + service.Key + "&format=json"
	} else if service.Type == "2" {
		url = "https://c.y.qq.com/soso/fcgi-bin/client_music_search_songlist?remoteplace=txt.yqq.playlist&page_no=" + strconv.FormatInt(newOffset-1, 10) + "&num_per_page=" + service.Limit + "&query=" + service.Key + "&format=json"
	} else if service.Type == "3" {
		url = "https://c.y.qq.com/soso/fcgi-bin/client_search_user?p=" + service.Offset + "&n=" + service.Limit + "&searchid=241014031194265199&remoteplace=txt.yqq.user&w=" + service.Key + "&format=json"
	}

	res, err := util.QQGet(url)
	if err != nil {
		return err
	}
	return serializer.OkResponse(res)
}

//获取热搜
func (service *Search) SearchHot() *serializer.Response {

	url := "https://c.y.qq.com/splcloud/fcgi-bin/gethotkey.fcg?format=json"

	res, err := util.QQGet(url)
	if err != nil {
		return err
	}
	return serializer.OkResponse(res)
}
